
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.SortProcess;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.SortProcessDAO;
import com.scalar.chiptrack.operations.process.forms.SortProcessForm;
import com.scalar.chiptrack.users.User;


/**
 * Implementation of <strong>Action</strong> that gives sort process
 * to create,modify and save the sort process
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.1.1.1 $ $Date: 2006/12/11 23:43:09 $
 */

public final class SortProcessAction extends ChipTrackAction {


    // ----------------------------------------------------- Instance Variables
    // removed by hareesh on 27th August 2003
    // when setuping the Sort bin, besure to umcomment this.
    // presently code for sort bin stepup is uncommtted
    // this is wrong of the to place the gobal varaibles here in Action Class.
      /*private int processStepId = -1;
       private int baseProductId = -1;
       private String fabProductName = null;
       private SortProcess sortProcess = null;*/
      // -- END --
    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {

		String action = request.getParameter("action");
		SortProcessForm subform = (SortProcessForm) form;
	    HttpSession ses = request.getSession(true);
		HashMap errors = new HashMap();           
	    // Validate the request parameters specified by the user
		ActionErrors err = new ActionErrors();

		User user = (User)ses.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}        
		if("CreateProcess".equals(action)) 
		{
	    	subform.setSortProcess(SortProcessDAO.getSortProcessInfo(
	                        request.getParameter("productID"),
	                        request.getParameter("previousStepID"),
	                        request.getParameter("stepName"),
	                        request.getParameter("trackID"),
	                        request.getParameter("fabProductName")));
	
			 request.setAttribute("sortProcessForm",subform);// Added by Raj Vallamsetla
			 subform.setAction(action); // do we need this, as we are showing two differenet pages
	         return (mapping.findForward("success"));
		}
	        
	    if("SortBinSetup".equals(action)) 
	    {
	        //check this and modify..try to put directly from subform itself
			SortProcess sortProcess =(SortProcess)subform.getSortProcess();
			sortProcess.setVendorLocations(getVendorLocations(request));
			subform.setSortProcess(sortProcess);
	        request.setAttribute("sortProcess", subform.getSortProcess());
	        subform.setSortProcess((SortProcess)request.getAttribute("sortProcess"));
			return (mapping.findForward("binsetup"));
	    }
	        
	    if("SaveSortBins".equals(action)) 
	    {
	       SortProcess sortProcess = subform.getSortProcess();
	       sortProcess.setSortBins(subform.getSortProcess().getSortBins());
	       subform.setSortProcess(sortProcess);
		   request.setAttribute("sortProcessForm",subform);
	       return (mapping.findForward("success"));
	    }
	        
		if("EditSortProcess".equals(action)) 
		{
	    	subform.setSortProcess(SortProcessDAO.getSortProcessInfo((String)request.getParameter("processStepID")));
            // added by hareesh on 6th October 2003
            // -- START --
            try{
                subform.getSortProcess().setTrackId( Integer.parseInt( request.getParameter("trackID") ) );
            }catch(NumberFormatException nfe){
                subform.getSortProcess().setTrackId(0);
            }
            // -- END --
			request.setAttribute("sortProcess", subform.getSortProcess());
			request.setAttribute("sortProcessForm",subform);// Added by Raj Vallamsetla
	        //Mallik..will take care from here...
	        return (mapping.findForward("success"));
		}
	        
	    if("SaveModifyProcess".equals(action)) 
	    {
	          //Mallik will take care from here...
	    }
	
		if("SaveSortProcess".equals(action)) 
		{
	        //Save the sort process information
		   SortProcess sortProcess = subform.getSortProcess();
		   sortProcess.setVendorLocations(getVendorLocations(request));
		   
		   
		   String[] partNumbers = new String[sortProcess.getDupProductName().length+1];
		   partNumbers[0] = sortProcess.getSortProductName();
		   for(int i=0; i < sortProcess.getDupProductName().length ; i++)
		   {
			   partNumbers[i+1] = sortProcess.getDupProductName()[i];
		   }
		   // added by ravikanth on 16 Sep 2003 
		   // check for duplicates in Product_Map_Table
		   String dupNames = ProductDao.checkDupInProductMapTable(partNumbers,sortProcess.getProcessStepId(),sortProcess.getProcessType());
		   if( dupNames.length() > 0 )
		   {

			   errors.put ("Part Numbers Already exists ", dupNames );
			   // changed by hareesh on 27th Stepember 2003
               // -- START --
               /* ArrayList vendorLocations = null;
               if(processStepId!=-1)
			   {
				   vendorLocations = VendorDAO.getSortLocations(processStepId);
			   }
			   else
			   {
				   vendorLocations = VendorDAO.getSortLocations();
			   } */
               // -- END --
			   request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
			   request.setAttribute( "sortProcess" , sortProcess );
			   request.setAttribute("sortProcessForm",subform);
			   return ( mapping.findForward("success") );
		   }
		   // upto here
		   
		   
		   sortProcess = null;
	       sortProcess = SortProcessDAO.saveSortProcessInfo(subform.getSortProcess());
	       
	       //System.out.println("Process type ********  "+sortProcess.getProcessType() );
	       
	       /*
	       System.out.println("before sending to transport processStepId  = " + sortProcess.getProcessStepId()+"");
	       System.out.println("before sending to sort proces form transport processStepId  = " + subform.getSortProcess().getProcessStepId()+"");
	       System.out.println("before sending to transport previousStepId = " + sortProcess.getPreviousStepId()+""); 
	       System.out.println("before sending to transport baseProductId = " + sortProcess.getBaseProductId()+"");
	       System.out.println("before sending to transport product name = " + sortProcess.getSortProductName()+"");  
	       System.out.println("before sending to transport trackId = " +  sortProcess.getTrackId()+"");
	       System.out.println("before sending to transport process type = " + sortProcess.getProcessType()+"");
	       
	        //Set the request parameters for transport
	        request.setAttribute ("processStepId", subform.getSortProcess().getProcessStepId()+"");                
	        request.setAttribute ("previousStepId", subform.getSortProcess().getPreviousStepId()+""); 
	        request.setAttribute ("baseProductId", subform.getSortProcess().getBaseProductId()+"");
	        request.setAttribute ("baseProductName", subform.getSortProcess().getSortProductName()+"");  
	        request.setAttribute ("trackId", subform.getSortProcess().getTrackId()+"");
	        request.setAttribute ("stepName", subform.getSortProcess().getProcessType()+"");
	        request.setAttribute ("comingFrom", "SORT");
	        */
	        request.setAttribute ("processStepId", sortProcess.getProcessStepId()+"");                
	        request.setAttribute ("previousStepId", sortProcess.getPreviousStepId()+""); 
	        request.setAttribute ("baseProductId", sortProcess.getBaseProductId()+"");
	        request.setAttribute ("baseProductName", sortProcess.getSortProductName()+"");  
	        request.setAttribute ("trackId", sortProcess.getTrackId()+"");
	        request.setAttribute ("stepName", sortProcess.getProcessType()+"");
	        request.setAttribute ("comingFrom", "SORT");
	       
	        return (mapping.findForward("transport"));
		}
	        
	     //If action is empty ...Add more bins...
	    if((action.equals("")) || (action == ""))
	          return (mapping.findForward("binsetup"));
	
		// Report any errors we have discovered back to the original form
		if (!err.empty()) 
		{
			saveErrors(request, err);
			return (new ActionForward(mapping.getInput()));
		}
	
		//Please look at this return later(Where do we need this retrurned) ???
		return (mapping.findForward("success"));
   }


	private ArrayList getVendorLocations (HttpServletRequest request) 
	{
        ArrayList vendorLocations = new ArrayList();
        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) 
        {
            return null;
        }
        
		String[] priority = request.getParameterValues("priority");
		String[] locationID = request.getParameterValues("locationID");;
		String[] split = request.getParameterValues("split");
		String[] capacityWeek = request.getParameterValues("capacityWeek");
		String[] normalCost = request.getParameterValues("normalCost");
		String[] expressCost = request.getParameterValues("expressCost");
		String[] normalCycleTime = request.getParameterValues("normalCycleTime");
		String[] expressCycleTime = request.getParameterValues("expressCycleTime");
	    String[] laserRepairCost = request.getParameterValues("laserRepairCost");
    
        VendorLocation location = null;
        String select = null;
        String laserRepair = null;
        
        for (int i=0; i<locationName.length; i++) 
        {
            select = request.getParameter("select_"+i);
			if(select==null)
			select=""; 	
              // changed by hareesh on 24th September 2003
                // -- START --
                /*location = new VendorLocation (priority[i],
                                                 locationName[i],
                                                 locationID[i],
                                                 split[i],
                                                 capacityWeek[i],
                                                 Float.parseFloat(normalCost[i]),
                                                 Float.parseFloat(expressCost[i]),
                                                 normalCycleTime[i],
                                                 expressCycleTime[i]);
                location.setLaserRepairCost (Float.parseFloat(laserRepairCost[i])); */

                location = new VendorLocation();
                location.setPriority( ( priority[i] != null && priority[i].trim().length() != 0) ? priority[i] : "0" );
                location.setLocationName( locationName[i] );
                location.setLocationID( locationID[i] );
                location.setSplit( ( split[i] != null && split[i].trim().length() != 0) ? split[i] : "0" );
                location.setCapacityWeek( ( capacityWeek[i] != null && capacityWeek[i].trim().length() != 0) ? capacityWeek[i] : "0" );
                location.setNormalCost( Float.parseFloat ( ( normalCost[i] != null && normalCost[i].trim().length() != 0) ? normalCost[i] : "0.0" ) );
                location.setExpressCost( Float.parseFloat( expressCost[i] != null && expressCost[i].trim().length() != 0 ? expressCost[i] : "0.0" ) ) ;
                location.setNormalCycleTime(( normalCycleTime[i] != null && normalCycleTime[i].trim().length() != 0) ? normalCycleTime[i] : "0" );
                location.setExpressCycleTime(( expressCycleTime[i] != null && expressCycleTime[i].trim().length() != 0) ? expressCycleTime[i] : "0"  );

                location.setSelect (select);
                laserRepair = request.getParameter ("laserRepairAllowed_"+i);
                if ((laserRepair == null) || (laserRepair.trim().length() == 0)) {
                    location.setLaserRepairAllowed (false);
                    location.setLaserRepairCost ( 0.0f ) ;
                }
                else {
                    location.setLaserRepairAllowed (true);
                    location.setLaserRepairCost ( Float.parseFloat( laserRepairCost[i]!= null && laserRepairCost[i].trim().length() != 0 ? laserRepairCost[i] : "0.0" ) ) ;
                }
                // -- END --
                vendorLocations.add (location);
        }
        return vendorLocations;
    }
}
